#pragma once
#include "muduo/net/TcpClient.h"
#include "muduo/net/TcpConnection.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/base/CountDownLatch.h"

#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"
#include "muduo/base/Logging.h"     //不加incllude可以吗
#include "muduo/base/Mutex.h"

#include "channel.hpp"
#include "worker.hpp"

using namespace std::placeholders;
class Connection
{
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
public:
    using Ptr = std::shared_ptr<Connection>;
    Connection(const std::string& serverip, uint16_t serverport, const AsyncWorker::Ptr& worker)
        :_latch(1)
        ,_client(worker->loopthread.startLoop(), muduo::net::InetAddress(serverip, serverport), "client")
        ,_dispatcher(std::bind(&Connection::onUnknownMessage, this, _1, _2, _3))
        ,_codec(std::make_shared<ProtobufCodec>(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, _1, _2, _3)))
        ,_worker(worker)
        ,_channelManager(std::make_shared<ChannelManager>())
    {
        _dispatcher.registerMessageCallback<basicConsumerResponse>(std::bind(&Connection::OnBasicConsumerResponseCallback, this, _1, _2, _3));
        _dispatcher.registerMessageCallback<basicCommonResponse>(std::bind(&Connection::OnBasicCommonResponseCallback, this, _1, _2, _3));
        _client.setConnectionCallback(std::bind(&Connection::OnConnectionCallback, this, _1));
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, _codec.get(), _1, _2, _3));
        
        _client.connect();
        _latch.wait();
    }
    // void Connect()
    // {

    // }
    Channel::Ptr openChannel()
    {
       // DLOG("本地？");
        Channel::Ptr channelPtr = _channelManager->openChannel(_conn, _codec);  //客户端创建信道
      //  DLOG("本地？");
        if(channelPtr.get() == nullptr)
        {
            DLOG("信道没有打开成功");
            return Channel::Ptr();
        }
       // DLOG("让远端生成一个报错吗");
        channelPtr->openChannel();              //让服务端也创建一个
       // DLOG("让远端生成一个报错吗");

        return channelPtr;
    }
    void closeChannel(const Channel::Ptr& channelPtr)
    {
        //DLOG("closeChannel");
        channelPtr->closeChannel();
        //DLOG("closeChannel");
        _channelManager->closeChannel(channelPtr->getCid());
        //DLOG("closeChannel");
    }
    ~Connection()
    {
       // DLOG("段错误");
    }
private:

    void onUnknownMessage(const muduo::net::TcpConnectionPtr& conn, const MessagePtr& message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }
    void OnBasicConsumerResponseCallback(const muduo::net::TcpConnectionPtr& conn, const basicConsumerResponsePtr& message, muduo::Timestamp)
    {
        Channel::Ptr channelPtr = _channelManager->getChannel(message->cid());
        if(channelPtr.get() == nullptr)
        {
            DLOG("信道id:%s, 没有对应的信道", message->cid().c_str());
            return;
        }
        _worker->threadpool.Push([channelPtr, message](){
            channelPtr->consumer(message);
        });
    }
    void OnBasicCommonResponseCallback(const muduo::net::TcpConnectionPtr& conn, const basicCommonResponsePtr& message, muduo::Timestamp)
    {
        Channel::Ptr channelPtr = _channelManager->getChannel(message->cid());
        if(channelPtr.get() == nullptr)
        {
            DLOG("信道id:%s, 没有对应的信道", message->cid().c_str());
            return;
        }
        channelPtr->putBasicResponse(message);
    }
    void OnConnectionCallback(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
             _conn = conn;
            _latch.countDown();
           
            std::cout << "链接成功" << std::endl;
        }
        else 
        {
            _conn.reset();            
            std::cout << "链接断开" << std::endl;
        }
    }
private:
    muduo::CountDownLatch _latch;
         
    muduo::net::TcpConnectionPtr _conn;
    muduo::net::TcpClient _client;                  //这两个地方写反，析构的时候会段错误
    

    ProtobufDispatcher _dispatcher;
    ProtobufCodecPtr _codec;

    ChannelManager::Ptr _channelManager;
    AsyncWorker::Ptr _worker;
};